import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { flightAPI } from '../../services/api';

// 异步thunks
export const fetchFlights = createAsyncThunk(
  'flights/fetchFlights',
  async (params = {}) => {
    const response = await flightAPI.getAllFlights(params);
    return response.data;
  }
);

export const searchFlights = createAsyncThunk(
  'flights/searchFlights',
  async ({ departure_city, arrival_city, departure_date }) => {
    const params = {
      departure_city,
      arrival_city,
      departure_date,
    };
    const response = await flightAPI.searchFlights(params);
    return response.data;
  }
);

export const fetchFlightById = createAsyncThunk(
  'flights/fetchFlightById',
  async (id) => {
    const response = await flightAPI.getFlightById(id);
    return response.data;
  }
);

export const createFlight = createAsyncThunk(
  'flights/createFlight',
  async (flightData) => {
    const response = await flightAPI.createFlight(flightData);
    return response.data;
  }
);

export const updateFlight = createAsyncThunk(
  'flights/updateFlight',
  async ({ id, data }) => {
    const response = await flightAPI.updateFlight(id, data);
    return response.data;
  }
);

export const deleteFlight = createAsyncThunk(
  'flights/deleteFlight',
  async (id) => {
    await flightAPI.deleteFlight(id);
    return id;
  }
);

const flightSlice = createSlice({
  name: 'flights',
  initialState: {
    flights: [],
    currentFlight: null,
    loading: false,
    error: null,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
    },
  },
  reducers: {
    clearCurrentFlight: (state) => {
      state.currentFlight = null;
    },
    clearError: (state) => {
      state.error = null;
    },
    setPagination: (state, action) => {
      state.pagination = { ...state.pagination, ...action.payload };
    },
  },
  extraReducers: (builder) => {
    builder
      // fetchFlights
      .addCase(fetchFlights.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchFlights.fulfilled, (state, action) => {
        state.loading = false;
        state.flights = action.payload.flights || action.payload;
        state.pagination.total = action.payload.total || action.payload.length;
      })
      .addCase(fetchFlights.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message;
      })
      // searchFlights
      .addCase(searchFlights.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(searchFlights.fulfilled, (state, action) => {
        state.loading = false;
        state.flights = action.payload;
        state.pagination.total = action.payload.length;
      })
      .addCase(searchFlights.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message;
      })
      // fetchFlightById
      .addCase(fetchFlightById.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchFlightById.fulfilled, (state, action) => {
        state.loading = false;
        state.currentFlight = action.payload;
      })
      .addCase(fetchFlightById.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message;
      })
      // createFlight
      .addCase(createFlight.fulfilled, (state, action) => {
        state.flights.unshift(action.payload);
      })
      // updateFlight
      .addCase(updateFlight.fulfilled, (state, action) => {
        const index = state.flights.findIndex(f => f.id === action.payload.id);
        if (index !== -1) {
          state.flights[index] = action.payload;
        }
      })
      // deleteFlight
      .addCase(deleteFlight.fulfilled, (state, action) => {
        state.flights = state.flights.filter(f => f.id !== action.payload);
      });
  },
});

export const { clearCurrentFlight, clearError, setPagination } = flightSlice.actions;
export default flightSlice.reducer;